package com.ruoyi.customers.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.customers.mapper.SysCustomersMapper;
import com.ruoyi.customers.domain.SysCustomers;
import com.ruoyi.customers.service.ISysCustomersService;

/**
 * 客户个人信息Service业务层处理
 * 
 * @author yhh
 * @date 2020-12-23
 */
@Service
public class SysCustomersServiceImpl implements ISysCustomersService 
{
    @Autowired
    private SysCustomersMapper sysCustomersMapper;

    /**
     * 查询客户个人信息
     * 
     * @param cusId 客户个人信息ID
     * @return 客户个人信息
     */
    @Override
    public SysCustomers selectSysCustomersById(Long cusId)
    {
        return sysCustomersMapper.selectSysCustomersById(cusId);
    }

    /**
     * 查询客户个人信息列表
     * 
     * @param sysCustomers 客户个人信息
     * @return 客户个人信息
     */
    @Override
    public List<SysCustomers> selectSysCustomersList(SysCustomers sysCustomers)
    {
        return sysCustomersMapper.selectSysCustomersList(sysCustomers);
    }

    /**
     * 新增客户个人信息
     * 
     * @param sysCustomers 客户个人信息
     * @return 结果
     */
    @Override
    public int insertSysCustomers(SysCustomers sysCustomers)
    {
        return sysCustomersMapper.insertSysCustomers(sysCustomers);
    }

    /**
     * 修改客户个人信息
     * 
     * @param sysCustomers 客户个人信息
     * @return 结果
     */
    @Override
    public int updateSysCustomers(SysCustomers sysCustomers)
    {
        return sysCustomersMapper.updateSysCustomers(sysCustomers);
    }

    /**
     * 批量删除客户个人信息
     * 
     * @param cusIds 需要删除的客户个人信息ID
     * @return 结果
     */
    @Override
    public int deleteSysCustomersByIds(Long[] cusIds)
    {
        return sysCustomersMapper.deleteSysCustomersByIds(cusIds);
    }

    /**
     * 删除客户个人信息信息
     * 
     * @param cusId 客户个人信息ID
     * @return 结果
     */
    @Override
    public int deleteSysCustomersById(Long cusId)
    {
        return sysCustomersMapper.deleteSysCustomersById(cusId);
    }

    @Override
    public JSONObject getSessionKeyOropenid(String code) {
        //微信端登录code值
        String wxCode = code;
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";  //请求地址 https://api.weixin.qq.com/sns/jscode2session
        Map<String, String> requestUrlParam = new HashMap<String, String>();
        requestUrlParam.put("appid", "你微信小程序的appID");  //开发者设置中的appId
        requestUrlParam.put("secret", "你微信小程序的appSecret"); //开发者设置中的appSecret
        requestUrlParam.put("js_code", wxCode); //小程序调用wx.login返回的code
        requestUrlParam.put("grant_type", "authorization_code");    //默认参数 authorization_code
        //发送post请求读取调用微信 https://api.weixin.qq.com/sns/jscode2session 接口获取openid用户唯一标识
        JSONObject jsonObject = JSON.parseObject(sendPost(requestUrl, requestUrlParam));
        return jsonObject;
    }

    public String sendPost(String url, Map<String, ?> paramMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";

        String param = "";
        Iterator<String> it = paramMap.keySet().iterator();

        while (it.hasNext()) {
            String key = it.next();
            param += key + "=" + paramMap.get(key) + "&";
        }

        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            // logger.error(e.getMessage(), e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 查询客户个人信息，如果是新用户则同时存入数据库里
     *
     * @param openid 客户个人openid
     * @return 结果
     */
    @Override
    public SysCustomers getcustomerInfo(String openid,String cusName,String cusImg,String cusSex){
        SysCustomers cus = new SysCustomers();
        SysCustomers cus2 = new SysCustomers();
        SysCustomers cusadd = new SysCustomers();
        cus = sysCustomersMapper.selectSysCustomersByOpenid(openid);
        if(cus == null){
            cusadd.setCusName(cusName);
            cusadd.setCusImg(cusImg);
            cusadd.setOpenid(openid);
            cusadd.setCusSex(cusSex);
            cusadd.setCusPoint((long)0);
            cusadd.setCusLevel("青铜会员");
            cusadd.setCusState("正常");
            sysCustomersMapper.insertSysCustomers(cusadd);
        }
        cus2 = sysCustomersMapper.selectSysCustomersByOpenid(openid);
        return cus2;
    }

    /**
     * 根据openid获取客户个人信息
     *
     * @param openid 客户个人openid
     * @return 结果
     */
    @Override
    public SysCustomers getcustomerInfobyopenid(String openid){
        return sysCustomersMapper.selectSysCustomersByOpenid(openid);
    }
    /**
     * 根据openid修改客户个人信息
     *
     * @param openid 客户个人openid
     * @return 结果
     */
    @Override
    public Boolean changeCustomerInfo(String openid,String phone){
        SysCustomers cus = new SysCustomers();
        cus = sysCustomersMapper.selectSysCustomersByOpenid(openid);
        cus.setCusTel(phone);
        if(sysCustomersMapper.updateSysCustomers(cus)>0){
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * 根据openid修改客户积分和会员等级
     *
     * @param openid 客户个人openid
     * @return 结果
     */
    @Override
    public Boolean updateCustomerLever(String openid,long point){
        SysCustomers cus = new SysCustomers();
        cus = sysCustomersMapper.selectSysCustomersByOpenid(openid);
        Long firpoint = cus.getCusPoint();
        Long newpoint = point+firpoint;
        String newlevel = new String();
        cus.setCusPoint(newpoint);
        if(newpoint>0){
            if(newpoint>=0&&newpoint<200){
                newlevel = "Lv0.青铜会员";
            }else if(newpoint>=200&&newpoint<400){
                newlevel = "Lv1.白银会员";
            }else if(newpoint>=400&&newpoint<600){
                newlevel = "Lv2.黄金会员";
            }else{
                newlevel = "Lv3.钻石会员";
            }
        }
        cus.setCusLevel(newlevel);
        if(sysCustomersMapper.updateSysCustomers(cus)>0){
            return true;
        }
        else {
            return false;
        }

    }


}
